<?php
namespace app\weapp\controller;

use app\common\controller\Weapp;
use app\weapp\library\WeAppApi;
use EasyWeChat\Work\Application;
use app\common\model\Member;
use think\facade\Db;
use app\admin\model\HrField;
use app\admin\model\HrFieldType;
use app\admin\model\HrGroupList;
use think\facade\Log;
class Service extends Weapp
{
    protected array $noNeedLogin = ['index','oauth','loginverify'];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = ['index','oauth','loginverify'];
    public function initialize(): void
    {
        parent::initialize();
    }

    public function index()
    {
        $config = [
            'corp_id' => 'ww5d7b19c3c1ce8e1f',
            'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
        ];
        $app = new Application($config);
        $callbackUrl = 'https://wework.sdlycwzx.com/index.php?s=weapp/service/oauth'; // 需设置可信域名
        $redirectUrl = $app->getOAuth()->redirect($callbackUrl);
        dump($redirectUrl);
    }
   
    public function oauth(){
        $code = $this->request->param('code','');
        $state = $this->request->param('state','');
        if(empty($code) || empty($state)){
            $this->error('用户识别失败');
        }
        $config = [
            'corp_id' => 'ww5d7b19c3c1ce8e1f',
            'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
        ];
        $app = new Application($config);
        $user = $app->getOAuth()->detailed()->userFromCode($code);
        $userinfo = $user->getRaw();
        $member = Member::getByUserId($userinfo['userid']);
 
        $member->nickname = $userinfo['name'];
        $member->save();
        $this->auth->login($userinfo['userid'],true);
        $token = $this->auth->getToken();
        Log::info('server:over');
        return redirect('https://wework.sdlycwzx.com/'.$state.'/#/pages/index/index?token='.$token,301);
    }
    
     public function oauth2(){
        $code = $this->request->param('code','');
        $state = $this->request->param('state','');
        if(empty($code) || empty($state)){
            $this->error('用户识别失败');
        }
        $config = [
            'corp_id' => 'ww5d7b19c3c1ce8e1f',
            'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
        ];
        $app = new Application($config);
        $user = $app->getOAuth()->detailed()->userFromCode($code);
        $userinfo = $user->getRaw();
       dump($userinfo);
    }
}